#include "threadPool.h"
int upload (int fd_socket, char *filename) {
    struct stat st;
    if (stat(filename, &st) == -1) {
        int flag = -1; // 文件不存在
        send(fd_socket, &flag, sizeof(int), MSG_NOSIGNAL);
        return -1;
    }

    int flag = S_ISREG(st.st_mode) ? 1 : 0; // 1:可传输, 0:不可传输
    if (send(fd_socket, &flag, sizeof(int), MSG_NOSIGNAL) <= 0) {
        return -1; // 发送失败
    }
    if (flag != 1) {
        return -1; // 文件不可传输
    }
    train_t train;
    memset(&train,0,sizeof(train_t));
    int fd =open(filename,O_RDONLY);
    //发送文件大小
    struct stat statbuf;
    memset(&statbuf,0,sizeof(statbuf));
    fstat(fd,&statbuf);
    printf("filesize=%ld\n",statbuf.st_size);
    off_t filesize=statbuf.st_size;
    train.len=sizeof(filesize);
    memcpy(train.buff,&statbuf.st_size,train.len);
    send(fd_socket,&train,sizeof(train.len)+train.len,MSG_NOSIGNAL);
    //发送文件
    while(1){
        bzero(train.buff,sizeof(train.buff));
        ssize_t sret=read(fd,train.buff,sizeof(train.buff));
        train.len=sret;
        send(fd_socket,&train,sizeof(train.len)+train.len,MSG_NOSIGNAL);
        if(sret==0){
            break;
        }
    }
    close(fd);
    return 0;
}
int download(int fd_socket, char *filename){
    int flag = -1;
    if (recv(fd_socket, &flag, sizeof(int), MSG_WAITALL) <= 0) {
        return -1; // 接收失败
    }
    if (flag != 1) {
        return -1; // 文件不可下载
    }

    //接受文件大小
    int fd=open(filename,O_WRONLY|O_CREAT|O_TRUNC,0666);
    off_t filesize;
    off_t cursize=0;
    train_t train;
    recv(fd_socket,&train.len,sizeof(train.len),0);
    recv(fd_socket,&train.buff,train.len,0);
    memcpy(&filesize,train.buff,train.len);
    printf("filesize=%ld\n",filesize);
    //接受文件内容
    while(1){
        bzero(train.buff,sizeof(train.buff));
        recv(fd_socket,&train.len,sizeof(train.len),MSG_WAITALL);
        if(train.len==0){
            break;
        }
        cursize+=train.len;
        if(cursize<filesize){
            printf("%5.2lf%%\r",1.00*cursize/filesize);
            fflush(stdout);
        }
        recv(fd_socket,train.buff,train.len,MSG_WAITALL);
        write(fd,train.buff,train.len);
    }

    printf("100.0%%\n");
    close(fd);
    return 0;
}

//打印命令
void printCmd(pCmd_t pcmd)
{
    printf("cmd: ");
    for (int i = 0; i < pcmd->_argc; ++i) {
        printf("%s ", pcmd->_cmd[i]);
    }
    printf("\n");
}

